import 'dart:convert';

import 'package:banyou_app/app/request/request_main.dart';
import 'package:banyou_app/app/util/common_utils.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../../util/string_util.dart';

class DongtaiController extends GetxController {
  final url = ''.obs;

  final title = ''.obs;

  final progress = 0.0.obs;
  final canGoBack = false.obs;

  WebViewController? webViewController;
  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    if (Get.arguments != null) {
      url.value = Get.arguments['url'];
      title.value = Get.arguments['title'];
    }
    super.onReady();
  }

  loadUrl() async {
    title.value = '';
    String key = box.read('key') ?? "";
    // if (isNotEmpty(key)) {
    if (isNotEmpty(url.value)) {
      if (webViewController != null) {
        webViewController!.reload();
      }
    } else {
      url.value = await RequestMain.getUrlStr(
          {'kefu': box.read('kefu') ?? "", 'key': key},
          'https://aqbanyou.olbibo.com.cn/find/?');
      print(url.value);
    }
    // }
  }
  void messageHandle(JavascriptMessage message) {
    String jsmessage = message.message.toString();

    print('=====jsmessage' + jsmessage);

    try {
      Map<String, dynamic> jsMap = json.decode(jsmessage);
      if (jsMap.isNotEmpty) {
        String type = jsMap["type"].toString();
        // 1、跳出APP外部在 safari 中打开，type=5,url=要打开的链接：
        // 2、内部H5跳转，type=15,url=要打开的链接
        // 3、重新获取消息未读数 type=999996：
        // 4、隐藏底部bar type=999997：
        // 5、显示底部bar type=999998：
        // 6、TD统计埋点 type=999999，两个参数：
        if (type == "5") {
          launchURL(Uri.parse(jsMap['url'].toString()));
        } else if (type == "15") {
          url.value = jsMap['url'];
          // title.value = jsMap['title'] ?? "";
          // Get.toNamed(Routes.ZHIYUE,
          //     arguments: {'url': url.value, title: title.value},
          //     preventDuplicates: false);
        } else if (type == "999996") {
          // Get.find<MineController>().loadunm();
        } else if (type == "999997") {
          canGoBack.value = true;

          // Get.find<TableController>().showAndHiddenTabbar(false);
        } else if (type == "999998") {
          canGoBack.value = false;
          // Get.find<TableController>().showAndHiddenTabbar(true);
        } else if (type == "999999") {
          // canGoBack.value = true;
          // Get.find<TabbarController>().showAndHiddenTabbar(true);
        }
      }
    } catch (e) {
      print('prase error');
      print(e);
    }
  }

  void launchURL(Uri apkUrl) async {
    if (await canLaunchUrl(apkUrl)) {
      await launchUrl(
        apkUrl,
      );
    }
  }

  @override
  void onClose() {}
}
